#include <stack>
#include <iostream>
#include <vector>
using namespace std;

class StackOfPlates
{
public:
    vector<stack<int>> stacks;
    int limit;
    StackOfPlates(int cap)
    {
        limit = cap;
    }

    void push(int val)
    {
        if (limit <= 0)
            return;
        if (stacks.empty() || stacks.back().size() == limit)
        {
            stacks.push_back(stack<int>());
        }
        stacks.back().push(val);
    }

    int pop()
    {
        return popAt(stacks.size() - 1);
    }

    int popAt(int index)
    {
        if (limit <= 0)
            return -1;
        if (index >= stacks.size() || index < 0)
            return -1;
        int val = stacks[index].top();
        stacks[index].pop();
        if (stacks[index].empty())
        {
            stacks.erase(stacks.begin() + index);
        }
        return val;
    }
};